
import { pAjax } from "../../index/javascripts/gather";
// 获取元素
const emptyBox = document.querySelector('.empty')
const cartBox = document.querySelector('.cart')

//获取到id和token
const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')


setLogin()
function setLogin() {
    if (!id || !token) return window.location.href = './login.html'
    getCartList()
}
async function getCartList() {

    let res = await pAjax({
        url: 'http://localhost:8888/cart/list',
        data: { id },
        headers: { authorization: token },
        dataType: 'json'
    })
    console.log(res);
    if (res.code !== 1) return window.location.href = './login.html'

    if (res.cart.length === 0) {
        emptyBox.classList.add('active')
        cartBox.classList.remove('active')
    } else {
        emptyBox.classList.remove('active')
        cartBox.classList.add('active')
        bindHtml(res.cart)
    }
}
function bindHtml(list) {
    let totalNum = 0, totalSelect = 0, totalPrice = 0
    list.forEach(item => {
        if (item.is_select) {
            totalNum += item.cart_number
            totalSelect++
            totalPrice += item.cart_number * item.current_price
        }
    })

    let str = `
        <div class="top">
            全选: <input class="selectAll" type="checkbox" ${totalSelect === list.length ? 'checked' : ''}>
        </div>
        <ul class="center">
        `
    list.forEach(item => {
        str += `
            <li>
                <div class="select">
                    <input data-id=${item.goods_id} type="checkbox" class="select_item" ${item.is_select ? 'checked' : ''}>
                </div>
                <div class="show">
                    <img src="${item.img_small_logo}" alt="">
                </div>
                <div class="title">${item.title}</div>
                <div class="price">￥${item.current_price}</div>
                <div class="number">
                    <button class="sub" data-id=${item.goods_id}>-</button>
                    <input type="text" value="${item.cart_number}">
                    <button class="add" data-id=${item.goods_id}>+</button>
                </div>
                <div class="subPrice">￥${item.cart_number * item.current_price}</div>
                <div class="del">
                    <button class="delBtn" data-id=${item.goods_id}>删除</button>
                </div>
            </li>
        `
    })
    str +=
        `
        </ul>
        <div class="bottom">
            <p>共计${totalNum}件商品</p>
            <div>
                <button class="clear">清空购物车</button>
                <button class="delAll" ${totalSelect === 0 ? 'disabled' : ''}>删除所有已选中</button>
                <button class="pay" ${totalSelect === 0 ? 'disabled' : ''}>去支付</button>
            </div>
            <p>总价￥ ${totalPrice.toFixed(2)}</p>
        </div>
    `
    cartBox.innerHTML = str
}

cartBox.addEventListener('click', async e => {
    e = e || window.event
    let target = e.target || e.srcElement

    if (target.className === 'select_item') {
        let goodsId = target.dataset.id - 0
        let res = await pAjax({
            url: 'http://localhost:8888/cart/select',
            data: { id, goodsId },
            method: 'post',
            dataType: 'json',
            headers: { authorization: token }
        })
        if (res.code === 1) {
            getCartList()
        }
    }

    if (target.className === 'delBtn') {
        let goodsId = target.dataset.id - 0
        let res = await pAjax({
            url: 'http://localhost:8888/cart/remove',
            data: { id, goodsId },
            dataType: 'json',
            headers: { authorization: token }
        })
        if (res.code === 1) {
            getCartList()
        }
    }

    if (target.className === 'add') {
        let goodsId = target.dataset.id - 0
        let n = target.previousElementSibling.value - 0
        let res = await pAjax({
            url: 'http://localhost:8888/cart/number',
            data: { id, goodsId, number: n + 1 },
            method: 'post',
            dataType: 'json',
            headers: { authorization: token }
        })
        console.log(res);
        if (res.code === 1) {
            getCartList()
        }
    }

    if (target.className === 'sub') {
        let goodsId = target.dataset.id - 0
        let n = target.nextElementSibling.value - 0
        if (n <= 1) return
        // console.log(n);
        let res = await pAjax({
            url: 'http://localhost:8888/cart/number',
            data: { id, goodsId, number: n - 1 },
            method: 'post',
            dataType: 'json',
            headers: { authorization: token }
        })
        if (res.code === 1) {
            getCartList()
        }
    }

    if (target.className === 'selectAll') {
        let type = target.checked ? 1 : 0
        let res = await pAjax({
            url: 'http://localhost:8888/cart/select/all',
            data: { id, type },
            method: 'post',
            dataType: 'json',
            headers: { authorization: token }
        })
        if (res.code === 1) {
            getCartList()
        }
    }
    if (target.className === 'delAll') {
        let res = await pAjax({
            url: 'http://localhost:8888/cart/remove/select',
            data: { id },
            dataType: 'json',
            headers: { authorization: token }
        })
        if (res.code === 1) {
            getCartList()
        }
    }
    // 清空购物车
    if (target.className === 'clear') {
        let res = await pAjax({
            url: 'http://localhost:8888/cart/clear',
            data: { id },
            dataType: 'json',
            headers: { authorization: token }
        })
        console.log(res);
        if (res.code === 1) {
            getCartList()
        }
    }
})

